package com.fubowen.reader.extension

import java.text.DateFormat
import java.text.DecimalFormat
import java.util.Date

const val B = 1L
const val KB = B * 1024
const val MB = KB * 1024
fun Long.toSizeString() = when (this) {
    in (0 until KB) -> this.divAppendUnit(B, "B")
    in (KB until MB) -> this.divAppendUnit(KB, "KB")
    else -> this.divAppendUnit(MB, "MB")
}

fun Long.divAppendUnit(other: Long, unit: String): String {
    if (this.rem(other) == 0L) {
        return "${this / other}${unit}"
    }
    return DecimalFormat("#.##").format(this / other.toFloat()) + unit
}

fun Long.toTimeString(): String {
    val date = Date(this)
    val dateFormat = DateFormat.getDateInstance()
    return dateFormat.format(date)
}